<template>
  <div class="search-stock-container">
    <!-- 加载动画 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <div class="loading-text">正在加载...</div>
    </div>
    <!-- 头部区域 -->
    <header class="header">
      <div class="header-content">
        <h1>搜索结果</h1>
        <div class="header-info" v-if="totalItems > 0">
          <span class="total-count">共 {{ totalItems }} 条结果</span>
          <span class="page-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 列表区域 -->
      <div class="stock-list" v-if="currentPageData.length > 0">
        <div
            class="stock-item"
            v-for="(stock, index) in currentPageData"
            :key="`${stock.stockSymbol}-${stock.stockNumber}`"
            @click="handleStockClick(stock, index)"
            :class="{ 'tapped': tappedIndex === index }"
        >
          <div class="stock-content">
            <div class="stock-main">
              <div class="stock-symbol">{{ stock.stockSymbol }}</div>
              <div class="stock-number">
                <span class="stock-number-label">代码</span>
                <span class="stock-number-value">{{ stock.stockNumber }}</span>
              </div>
            </div>
            <div class="stock-actions">
              <div class="click-indicator">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="9,18 15,12 9,6"></polyline>
                </svg>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="!loading">
        <div class="empty-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <circle cx="11" cy="11" r="8"></circle>
            <path d="m21 21-4.35-4.35"></path>
          </svg>
        </div>
        <h2>暂无搜索结果</h2>
        <p>没有找到相关的股票信息</p>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-wrapper" v-if="totalPages > 1">
        <div class="pagination">
          <!-- 上一页 -->
          <button
              class="pagination-btn pagination-prev"
              :disabled="currentPage === 1"
              @click="goToPage(currentPage - 1)"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="15,18 9,12 15,6"></polyline>
            </svg>
            <span class="btn-text">上一页</span>
          </button>

          <!-- 页码 -->
          <div class="pagination-numbers">
            <button
                v-for="page in visiblePages"
                :key="page"
                class="pagination-number"
                :class="{
                'active': page === currentPage,
                'ellipsis': page === '...'
              }"
                @click="page !== '...' && goToPage(page)"
                :disabled="page === '...'"
            >
              {{ page }}
            </button>
          </div>

          <!-- 下一页 -->
          <button
              class="pagination-btn pagination-next"
              :disabled="currentPage === totalPages"
              @click="goToPage(currentPage + 1)"
          >
            <span class="btn-text">下一页</span>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="9,18 15,12 9,6"></polyline>
            </svg>
          </button>
        </div>

        <!-- 跳转到指定页 -->
        <div class="page-jumper">
          <span>跳转到</span>
          <input
              type="number"
              v-model.number="jumpPage"
              :min="1"
              :max="totalPages"
              @keyup.enter="handlePageJump"
              class="page-input"
          />
          <span>页</span>
          <button @click="handlePageJump" class="jump-btn">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'SearchStock',
  props: {
    searchResults: {
      type: Array,
      default: () => []
    },
    pageSize: {
      type: Number,
      default: 10
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()

    // 响应式数据
    const stockData = ref([])
    const currentPage = ref(1)
    const tappedIndex = ref(-1)
    const jumpPage = ref(1)
    const loading = ref(true)

    // 计算属性
    const totalItems = computed(() => stockData.value.length)
    const totalPages = computed(() => Math.ceil(totalItems.value / props.pageSize))

    // 当前页数据
    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * props.pageSize
      const end = start + props.pageSize
      return stockData.value.slice(start, end)
    })

    // 可见页码
    const visiblePages = computed(() => {
      const pages = []
      const total = totalPages.value
      const current = currentPage.value

      if (total <= 7) {
        // 总页数少于等于7页，显示全部
        for (let i = 1; i <= total; i++) {
          pages.push(i)
        }
      } else {
        // 总页数大于7页，显示省略号
        if (current <= 4) {
          // 当前页在前4页
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        } else if (current >= total - 3) {
          // 当前页在后4页
          pages.push(1)
          pages.push('...')
          for (let i = total - 4; i <= total; i++) {
            pages.push(i)
          }
        } else {
          // 当前页在中间
          pages.push(1)
          pages.push('...')
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        }
      }

      return pages
    })

    // 初始化数据
    const initializeData = () => {
      loading.value = true
      setTimeout(() => { // 模拟异步加载
        if (props.searchResults && props.searchResults.length > 0) {
          stockData.value = props.searchResults
        } else if (route.query.data) {
          try {
            stockData.value = JSON.parse(route.query.data)
          } catch (error) {
            console.error('解析路由数据失败:', error)
            stockData.value = getDefaultData()
          }
        } else {
          stockData.value = getDefaultData()
        }
        loading.value = false
      }, 400) // 可根据实际接口调整
    }

    // 获取默数据
    const getDefaultData = () => {
      const baseData =JSON.parse(route.query.stockData)
      return baseData
    }

    // 跳转到指定页
    const goToPage = (page) => {
      if (page >= 1 && page <= totalPages.value) {
        loading.value = true
        setTimeout(() => {
          currentPage.value = page
          jumpPage.value = page
          // 滚动到顶部
          scrollToTop()
          loading.value = false
        }, 300)
      }
    }

    // 滚动到顶部
    const scrollToTop = () => {
      // 方案1: 尝试滚动到当前组件的容器顶部
      const container = document.querySelector('.search-stock-container')
      if (container) {
        container.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        })
        return
      }

      // 方案2: 查找可滚动的父容器
      const scrollableParent = findScrollableParent()
      if (scrollableParent && scrollableParent !== document.body && scrollableParent !== document.documentElement) {
        scrollableParent.scrollTo({
          top: 0,
          behavior: 'smooth'
        })
        return
      }

      // 方案3: 尝试滚动到头部
      const header = document.querySelector('.header')
      if (header) {
        header.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        })
        return
      }

      // 方案4: 滚动页面到顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    }

    // 查找可滚动的父容器
    const findScrollableParent = () => {
      let element = document.querySelector('.search-stock-container')

      while (element && element !== document.body) {
        const { overflow, overflowY, overflowX } = window.getComputedStyle(element)
        const isScrollable = ['auto', 'scroll'].includes(overflow) ||
            ['auto', 'scroll'].includes(overflowY) ||
            ['auto', 'scroll'].includes(overflowX)

        if (isScrollable && element.scrollHeight > element.clientHeight) {
          return element
        }

        element = element.parentElement
      }

      return null
    }

    // 处理页码跳转
    const handlePageJump = () => {
      if (jumpPage.value >= 1 && jumpPage.value <= totalPages.value) {
        goToPage(jumpPage.value)
      }
    }

    // 处理股票点击事件
    const handleStockClick = (stock, index) => {
      tappedIndex.value = index
      setTimeout(() => {
        tappedIndex.value = -1
      }, 300)

      console.log('点击了股票:', stock)

      // 跳转到股票详情页面
      router.push({
        path: '/center/stockInformation',
        query: {
          stockSymbol: stock.stockSymbol,
          stockNumber: stock.stockNumber
        }
      }).catch(error => {
        // 如果路由不存在，输出提示
        console.log('跳转失败，请配置对应路由:', error)
        alert(`点击了股票: ${stock.stockSymbol} (${stock.stockNumber})`)
      })
    }

    // 监听props变化
    watch(() => props.searchResults, (newData) => {
      if (newData && newData.length > 0) {
        stockData.value = newData
        currentPage.value = 1
        // 数据更新时也滚动到顶部
        setTimeout(scrollToTop, 100)
      }
    })

    onMounted(() => {
      initializeData()
    })

    return {
      stockData,
      currentPage,
      totalItems,
      totalPages,
      currentPageData,
      visiblePages,
      tappedIndex,
      jumpPage,
      goToPage,
      handlePageJump,
      handleStockClick,
      scrollToTop,
      findScrollableParent,
      loading
    }
  }
}
</script>

<style scoped>
.search-stock-container {
  min-height: 100vh;
  background-color: #fafafa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-bottom: 1px solid #e9ecef;
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.header-content {
  padding: 20px 0;
  text-align: center;
}

.header h1 {
  font-size: 24px;
  font-weight: 700;
  color: #212529;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.header-info {
  display: flex;
  justify-content: center;
  gap: 16px;
  font-size: 14px;
  color: #6c757d;
}

.total-count {
  font-weight: 600;
}

.page-info {
  color: #495057;
}

/* 主内容区域 */
.main-content {
  padding: 24px 16px;
  max-width: 800px;
  margin: 0 auto;
}

/* 列表样式 */
.stock-list {
  margin-bottom: 32px;
}

.stock-item {
  background: #ffffff;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  margin-bottom: 16px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.stock-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4px;
  background: #dee2e6;
  transition: background-color 0.25s ease;
}

.stock-item:hover {
  border-color: #6c757d;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.stock-item:hover::before {
  background: #495057;
}

.stock-item:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.stock-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stock-main {
  flex: 1;
}

.stock-symbol {
  font-size: 20px;
  font-weight: 700;
  color: #212529;
  margin-bottom: 6px;
  letter-spacing: 0.5px;
}

.stock-number {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stock-number-label {
  font-size: 12px;
  color: #868e96;
  background: #f8f9fa;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.stock-number-value {
  font-size: 15px;
  color: #495057;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, monospace;
  font-weight: 600;
}

.stock-actions {
  display: flex;
  align-items: center;
}

.click-indicator {
  color: #adb5bd;
  transition: all 0.2s ease;
}

.stock-item:hover .click-indicator {
  color: #495057;
  transform: translateX(2px);
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #6c757d;
}

.empty-icon {
  margin-bottom: 24px;
  color: #adb5bd;
}

.empty-state h2 {
  font-size: 20px;
  margin-bottom: 8px;
  color: #495057;
  font-weight: 600;
}

.empty-state p {
  font-size: 16px;
  color: #6c757d;
}

/* 分页样式 */
.pagination-wrapper {
  background: #ffffff;
  border-radius: 16px;
  padding: 24px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.pagination-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  border: 1px solid #dee2e6;
  background: #ffffff;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.pagination-btn:hover:not(:disabled) {
  border-color: #495057;
  background: #f8f9fa;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-text {
  white-space: nowrap;
}

.pagination-numbers {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.pagination-number {
  min-width: 40px;
  height: 40px;
  border: 1px solid #dee2e6;
  background: #ffffff;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  font-weight: 500;
  color: #495057;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-number:hover:not(:disabled):not(.ellipsis) {
  border-color: #495057;
  background: #f8f9fa;
}

.pagination-number.active {
  background: #212529;
  border-color: #212529;
  color: #ffffff;
}

.pagination-number.ellipsis {
  cursor: default;
  border: none;
  background: transparent;
}

/* 页码跳转 */
.page-jumper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  color: #495057;
  flex-wrap: wrap;
}

.page-input {
  width: 60px;
  padding: 6px 8px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.page-input:focus {
  outline: none;
  border-color: #495057;
}

.jump-btn {
  padding: 6px 12px;
  border: 1px solid #dee2e6;
  background: #ffffff;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #495057;
}

.jump-btn:hover {
  border-color: #495057;
  background: #f8f9fa;
}

/* 点击反馈动画 */
@keyframes tap-feedback {
  0% { background-color: #ffffff; }
  50% { background-color: #f8f9fa; }
  100% { background-color: #ffffff; }
}

.stock-item.tapped {
  animation: tap-feedback 0.3s ease;
}

/* 加载动画 */
.loading-overlay {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  background: none;
}
.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #e9ecef;
  border-top: 4px solid #495057;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
  background: none;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.loading-text {
  color: #495057;
  font-size: 16px;
  font-weight: 500;
  background: none;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .header {
    padding: 0 12px;
  }

  .header-content {
    padding: 16px 0;
  }

  .header h1 {
    font-size: 20px;
  }

  .header-info {
    flex-direction: column;
    gap: 4px;
  }

  .main-content {
    padding: 16px 12px;
  }

  .stock-item {
    padding: 16px;
    margin-bottom: 12px;
  }

  .stock-symbol {
    font-size: 18px;
  }

  .stock-number-value {
    font-size: 14px;
  }

  .pagination {
    gap: 6px;
  }

  .pagination-btn {
    padding: 8px 12px;
  }

  .btn-text {
    display: none;
  }

  .pagination-number {
    min-width: 36px;
    height: 36px;
  }

  .page-jumper {
    font-size: 13px;
  }

  .pagination-wrapper {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .stock-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .stock-actions {
    align-self: flex-end;
  }
}
</style>